import os
import json
from django.shortcuts import render
from user_system import models
from k8sMp.url_dict import url_json
from django.http import JsonResponse
from k8sMp.settings import BASE_DIR
from utils.auth_manog import auth_manog_done

@auth_manog_done
def role_list(request):
    if request.method == "GET":
        role_lists = models.UserType.objects.all()
        return render(request,"super_cmdb/role_list.html",{"role_lists":role_lists})

@auth_manog_done
def role_add(request):
    if request.method == "GET":
        return render(request,"super_cmdb/role_add.html")
    if request.method == "POST":
        role_name = request.POST.get("role_name")
        try:
            if not models.UserType.objects.filter(name=role_name).first():
                models.UserType.objects.create(name=role_name)
                msg = {"code": 0,"message": "添加角色成功"}
            else:
                msg = {"code": 1, "message": "添加角色失败，角色已存在"}
        except Exception as e:
            error = '异常：%s ,异常文件：%s ,异常行号：%s' % (e,
                                                 e.__traceback__.tb_frame.f_globals['__file__'],
                                                 e.__traceback__.tb_lineno)
            msg = {"code": 2, "message": error}
        return JsonResponse(msg)


@auth_manog_done
def role_permissions_setting(request,role_id):
    role_permissions_file = os.path.join(BASE_DIR, "k8sMp", "role_permissions_file.json")
    with open(role_permissions_file,"r",encoding="utf-8") as f:
        role_permissions_dict = json.loads(f.read())
    #print(type(role_permissions_dict))
    if role_id in role_permissions_dict.keys():
        current_role_permissions_list = role_permissions_dict[role_id]
    else:
        current_role_permissions_list = []
    if request.method == "GET":
        role_info = models.UserType.objects.filter(id=role_id).first()
        return render(request,"super_cmdb/role_permissions_setting.html",{
            "url_json":url_json,
            "role_info":role_info,
            "current_role_permissions_list":current_role_permissions_list
        })
    if request.method == "POST":
        try:
            permissions_list = request.POST.getlist("permissions_list")
            role_permissions_dict[role_id] = permissions_list
            #print(role_permissions_dict)
            role_permissions_dict = json.dumps(role_permissions_dict,sort_keys=True,indent=4)
            with open(role_permissions_file,"w",encoding="utf-8") as f:
                f.write(role_permissions_dict)
            msg = {"code": 0,"message": "角色权限配置成功"}
        except Exception as e:
            print(e)
            print('异常文件：%s ,异常行号：%s' % (e.__traceback__.tb_frame.f_globals['__file__'], e.__traceback__.tb_lineno))
            msg = {"code": 1, "message": "角色权限配置失败，异常文件：%s ,异常行号：%s"% (e.__traceback__.tb_frame.f_globals['__file__'], e.__traceback__.tb_lineno)}
        return JsonResponse(msg)
